//
//  SPNetworkManager.swift
//  Swift-demo
//
//  Created by zcp on 2021/9/25.
//


import Alamofire
import ObjectMapper
import Moya
import HandyJSON
import MBProgressHUD

//open class SPNetworkManager: NSObject {
//    static func getRequest(url: String,param: [String: AnyObject]) -> Void {
//        AF.request(url, method: .get, parameters: param).responseJSON { response in
////            let text: String = NSString(data: response.data!, encoding: String.Encoding.utf8.rawValue)! as String
//////                HDLog.LogOut("Data" as AnyObject, obj: text as AnyObject)
////            print("Data\(text as AnyObject)")
////            let hdHM01Response = Mapper<HDHM01Response>().map(JSONObject: response.result["data"]["returnData"])
//            print(response)
////            Mapper.toJSON(response.result.value)
//            if !JSONSerialization.isValidJSONObject(response.result) {
//                      print("is not a valid json object")
//            }
//            let Json2 = try? JSONSerialization.jsonObject(with: response.data!, options: .allowFragments) as! NSDictionary
//
////            print(Json2!["data"][""])
//
//
//        }
//    }
//}
//class HDHM01Response: Mappable {
//
//    var request_id:String?
////    var result:HDHM01Result?
//
//    init(){}
//
//    required init?(map: Map){
//        mapping(map:map)
//    }
//    func mapping(map: Map) {
//
//        request_id <- map["request_id"]
////        result <- map["result"]
//
//    }
//
//}

let timeoutClosure = {(endpoint: Endpoint, closure: MoyaProvider.RequestResultClosure) -> Void in
    if  var urlRequest = try? endpoint.urlRequest() {
        urlRequest.timeoutInterval = 20
        closure(.success(urlRequest))
    }else{
        closure(.failure(MoyaError.requestMapping(endpoint.url)))
    }
}

enum Api {
    case findHome
    case comicIntro(comicid: Int)
}

extension Api: TargetType {
    var headers: [String : String]? {
        return nil
    }
    
    var baseURL: URL {
        return URL(string: "https://app.u17.com/v3/appV3_3/ios/phone")!
    }
    
    var path: String {
        switch self {
        case .findHome: return "comic/getDetectListV4_5"
        case .comicIntro: return ""
            
        }
    }
    
    var method: Moya.Method {
        return .get
    }
    
    var sampleData: Data {
        return "".data(using: String.Encoding.utf8)!
    }
    
    var task: Task {
        var params: [String: Any] = [:]
        switch self {
        case .comicIntro(comicid: let comicid):
            params["comicid"] = comicid
        default: break
        }
        return .requestParameters(parameters: params, encoding: URLEncoding.default)
    }
}

let ApiProvider = MoyaProvider<Api>( requestClosure: timeoutClosure)
//
//let ApiProvider = MoyaProvider( requestClosure: <#T##MoyaProvider<_>.RequestClosure##MoyaProvider<_>.RequestClosure##(Endpoint, @escaping MoyaProvider<_>.RequestResultClosure) -> Void#>, plugins: <#T##[PluginType]#>)

//typealias Completion = (_ returnData: Dictionary<String, Any>) -> Void

extension Response {
    func mapModel<T: HandyJSON>(_ type: T.Type) throws -> T {
        let jsonSting = String(data: data, encoding: .utf8)
        guard let model = JSONDeserializer<T>.deserializeFrom(json: jsonSting) else {
            throw MoyaError.jsonMapping(self)
        }
        return model
    }
}


extension  MoyaProvider {
    @discardableResult
    open func getRequest<T: HandyJSON>(_ target: Target,
                                       model: T.Type,
                                       completion:((_ returnData: T?) -> Void)?) -> Cancellable? {
        return request(target, completion: { (result) in
            guard let completion = completion else { return }
            switch result {
            case let .success(value):
                guard let returnData = try? value.mapModel(ResponseData<T>.self) else {
                    completion(nil)
                    return
                }
                completion(returnData.data?.returnData)
            case let .failure(error):
                print(error)
            }

            

        })
    }
}
